package com.bicon.botu.mall.goods.api;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.entity.*;
import com.bicon.botu.mall.goods.service.*;
import com.bicon.botu.mall.goods.vo.ProductListVo;
import com.bicon.botu.mall.goods.vo.ProductPriceVo;
import com.bicon.botu.mall.goods.vo.TranceVo;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 类功能描述
 *
 * @author SYG
 * @date 2017/7/29
 */
@CrossOrigin
@RestController
@RequestMapping("/V1.0.0/api/productList")
public class ProductListApi extends BaseController {


    @Autowired
    private IProductService productService;

    @Autowired
    private IProductPictureService pictrueService;

    @Autowired
    private IProductRepertoryService repertoryService;

    @Autowired
    private ITraceElementService elementService;

    @Autowired
    private ITranceInfoService tranceInfoService;

    @Autowired
    private ITranceDetailService tranceDetailService;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private RedisHandler redisHandler;


    /**
     * 商品列表查询
     *
     * @param categoryPath 分类path
     * @param productName  商品名称
     * @param salesUp      销量
     * @param priceDown    价格
     * @param brand        品牌
     * @param minPrice     最小价格
     * @param maxPrice     最大价格
     * @param pageSize     显示条数
     * @param pageNo       当前页码
     * @return
     */
    @RequestMapping("getProductList")
    public BaseResult getProductList(@RequestParam(value = "categoryPath", required = false) String categoryPath,
                                     @RequestParam(value = "productName", required = false) String productName,
                                     @RequestParam(value = "salesUp", required = false) String salesUp,
                                     @RequestParam(value = "priceDown", required = false) String priceDown,
                                     @RequestParam(value = "brand", required = false) String brand,
                                     @RequestParam(value = "minPrice", required = false) Double minPrice,
                                     @RequestParam(value = "maxPrice", required = false) Double maxPrice,
                                     @RequestParam(value = "ids", required = false) String ids,
                                     @RequestParam("pageSize") Integer pageSize, @RequestParam("pageNo") Integer pageNo
    ) {
        Map<String, Object> map = new HashMap<>();
        Page page = new Page(pageNo, pageSize);
        boolean sort = false;
        if (!StringUtils.isEmpty(categoryPath)) {
            map.put("categoryId", categoryPath);
        }
        if (!StringUtils.isEmpty(productName)) {
            map.put("productName", "%" + productName + "%");
        }
        if (!StringUtils.isEmpty(salesUp)) {
            //按销量升序或降序排序
            if ("1".equals(salesUp)) {
                sort = true;
            }
            map.put("salesUp", sort);
            page.setOrderByField("sales");
            page.setAsc(sort);
        }
        if (!StringUtils.isEmpty(priceDown)) {
            if ("1".equals(priceDown)) {
                sort = true;
            }
            map.put("priceDown", sort);
            //按价格升序或降序排序
            page.setOrderByField("product_price");
            page.setAsc(sort);
        }
        if (!StringUtils.isEmpty(brand)) {
            map.put("brand", brand.split(","));
        }
        if (!StringUtils.isEmpty(minPrice) && !StringUtils.isEmpty(maxPrice)) {
            map.put("minPrice", minPrice);
            map.put("maxPrice", maxPrice);
        }
        if (!StringUtils.isEmpty(ids)) {
            map.put("ids", ids.split(","));
        }
        Page<ProductListVo> listVoPage = productService.getProductList(page, map);
        //获取列表中的最大金额和最小金额
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, listVoPage);
    }


    /**
     * 商品列表界面筛选接口
     *
     * @param categoryPath 分类path
     * @param productName  商品名称
     * @param brand        品牌ids
     * @param ids          商品ids
     * @return
     */
    @RequestMapping("getScreenData")
    public BaseResult getScreenData(@RequestParam(value = "categoryPath", required = false) String categoryPath,
                                    @RequestParam(value = "productName", required = false) String productName,
                                    @RequestParam(value = "brand", required = false) String brand,
                                    @RequestParam(value = "ids", required = false) String ids
                                   ){
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapAll = new HashMap<>();
        Page page = new Page(1, 1000);
        if (!StringUtils.isEmpty(categoryPath)) {
            map.put("categoryPath", categoryPath);
        }
        if (!StringUtils.isEmpty(productName)) {
            map.put("productName", "%" + productName + "%");
        }

        if (!StringUtils.isEmpty(brand)) {
            map.put("brand_id", brand.split(","));
        }

        if (!StringUtils.isEmpty(ids)) {
            map.put("ids", ids.split(","));
        }
        Page<ProductListVo> listVoPage = productService.getProductList(page, map);
        List<ProductListVo> listVos = listVoPage.getRecords();
        Set<String> brandList = new HashSet();
        for (ProductListVo vo:listVos){
            brandList.add(vo.getBrandId());
        }
        List<String> listString = new ArrayList<>(brandList);
        List<Brand> brandList1 = new ArrayList<>();
        if (listString.size() > 0) {
            brandList1 = brandService.selectBatchIds(listString);
        }
        ProductPriceVo priceVo = productService.getMaxPriceAndMinPrice(map);
        List<Integer[]> list = new ArrayList<>();
        if (null != priceVo) {
            Integer minPrice1 = priceVo.getMinPrice();
            Integer maxPrice1 = priceVo.getMaxPrice();
            Integer newPrice = (maxPrice1 - minPrice1) / 3;
            Integer [] first=  new Integer[]{minPrice1,newPrice};
            Integer [] second=  new Integer[]{newPrice,newPrice*2};
            Integer [] third=  new Integer[]{newPrice*2,maxPrice1};
            list.add(first);
            list.add(second);
            list.add(third);
        }
        mapAll.put("price",list);
        mapAll.put("brand",brandList1);
        return sendResult(GoodsConstants.RESPONSE_CODE_200,GoodsConstants.RESPONSE_MESSAGE_200,mapAll);

    }

    /**
     * 查询商品详细信息
     *
     * @param productId
     * @return
     */
    @RequestMapping("getProductInfo")
    public BaseResult getProductInfo(@RequestParam("productId") String productId, @RequestParam(value = "userId", required = false) String userId, HttpServletRequest request) {

        Map<String, Object> map = new HashedMap();
        //查询商品信息
        Product product = productService.selectById(productId);
        //查询商品图片
        List<ProductPicture> pictrueList = pictrueService.selectList(new EntityWrapper<ProductPicture>().eq("product_id", productId));
        //查询商品详细信息
        List<ProductRepertory> repertoryList = repertoryService.selectList(new EntityWrapper<ProductRepertory>().eq("product_id", productId).eq("logic_delete",GoodsConstants.DEL_LOGIC_NORMAL));
        //如果该商品是定制商品
        if (null == product) {
            return sendResult(GoodsConstants.RESPONSE_CODE_602, GoodsConstants.RESPONSE_MESSAGE_602);
        }
        if (product.getProductType().equals(GoodsConstants.CUSTOM_STATE1)) {
            map.put("productTrance", GoodsConstants.CUSTOM_STATE1);
            //查询该用户是否已完成定制
            TranceInfo info = tranceInfoService.selectOne(new EntityWrapper<TranceInfo>().eq("product_id", productId).eq("user_id", userId));
            TranceVo vo = new TranceVo();
            if (null != info) {
                //已定制
                map.put("TranceState", GoodsConstants.CUSTOM_STATE1);
                List<TranceDetail> detailList = tranceDetailService.selectList(new EntityWrapper<TranceDetail>().eq("trance_info_id", info.getId()));
                vo.setId(info.getId());
                vo.setProductId(info.getProductId());
                vo.setUserId(info.getUserId());
                vo.setBeforeText(info.getBeforeText());
                vo.setAfterText(info.getAfterText());
                vo.setDetailList(detailList);
                map.put("tranceInfo", vo);
            } else {
                //未完成定制
                map.put("TranceState", GoodsConstants.CUSTOM_STATE2);
                List<TraceElement> elementList = elementService.selectList(new EntityWrapper<TraceElement>().eq("product_id", productId));
                map.put("elementList", elementList);
            }
        } else {
            map.put("productTrance", GoodsConstants.CUSTOM_STATE2);
        }
        //如果不是免运费商品
        if("2".equals(product.getIsFreeFreight())){
          map.put("logistics",productService.selectLogisticsCenter(productId));
        }
        String address = redisHandler.getGlobalRedisTemplate().getHash(GoodsConstants.H5, "", GoodsConstants.H5_KEY);
        map.put("product", product);
        map.put("pictureList", pictrueList);
        map.put("repertoryList", repertoryList);
        map.put("h5Url",address+productId);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, map);
    }


}
